package com.gz.moreaseManager.modules.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.gz.moreaseManager.config.SelfUserDetails;
import com.gz.moreaseManager.core.base.BaseController;
import com.gz.moreaseManager.core.base.Constants;
import com.gz.moreaseManager.core.modal.AjaxResult;
import com.gz.moreaseManager.core.modal.HttpCode;
import com.gz.moreaseManager.core.modal.PageResult;
import com.gz.moreaseManager.modules.entity.Banner;
import com.gz.moreaseManager.modules.entity.Brand;
import com.gz.moreaseManager.modules.service.IBrandService;
import com.gz.moreaseManager.modules.service.IMenuWebService;
import com.gz.moreaseManager.utils.DateUtil;
import com.gz.moreaseManager.utils.UtilTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wike
 * @since 2019-02-25
 */
@RestController
@RequestMapping("/brand")
public class BrandController extends BaseController {

    @Autowired
    private IBrandService brandService;
    @Autowired
    private IMenuWebService menuWebService;

    @GetMapping("list")
    public ModelAndView list(){
        return new ModelAndView("modules/brand/list");
    }

    @GetMapping("add")
    public ModelAndView add(){
        return new ModelAndView("modules/brand/add");
    }

    @GetMapping("update")
    public ModelAndView update(Integer brandId){
        Brand brand = brandService.selectById( brandId );
        ModelAndView module = new ModelAndView("modules/brand/update");
        module.addObject("brand",brand);
        return module;
    }

    @GetMapping("listPage")
    public PageResult<Brand> findPageLsit(String brandName,Integer type,
                                          @DateTimeFormat(pattern = "yyyy-MM-dd")Date startDate,
                                          @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate,
                                          Integer pageNum, Integer pageSize){
        //分页
        Page paramsPage = new Page();
        paramsPage.setCurrent(pageNum);
        paramsPage.setSize(pageSize);
        //构建查询
        Wrapper wrapper = new EntityWrapper<Banner>();
        if( UtilTool.isNotBlank( brandName ))
            wrapper.like("brand_name",brandName);
        if( UtilTool.isNotBlank( type ))
            wrapper.eq("type",type);
        if( UtilTool.isNotBlank( startDate ) ){
            if( UtilTool.isNotBlank( endDate ) && startDate.getTime() == endDate.getTime() ){
                wrapper.between("release_time",startDate,DateUtil.addDays(startDate,1));
            }else{
                wrapper.between("release_time",startDate,
                        UtilTool.isNotBlank(endDate)?DateUtil.addDays(endDate,1):DateUtil.addDays(new Date(),1));
            }
        }
        if( UtilTool.isBlank(startDate) && UtilTool.isNotBlank( endDate )){
            wrapper.le("release_time",DateUtil.addDays(endDate,1));
        }
        //排序
        wrapper.orderBy("release_time",false);

        Page<Brand> data = brandService.selectPage(paramsPage,wrapper);
        return new PageResult(0, null, data.getTotal(), data.getRecords());

    }

    /**
     * 新增品牌
     * @param brand
     * @return
     */
    @PostMapping("addBrand")
    public AjaxResult<Boolean> addBrand(@RequestBody  Brand brand ,Authentication authentication){
        if( brand == null
                || UtilTool.isBlank( brand.getBrandName())
                || UtilTool.isBlank( brand.getType())
                || UtilTool.isBlank( brand.getReleaseTime()))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");

        /*if( UtilTool.isNotBlank( brand.getUploadImg()) ){
            String imgUrl = BaseCommonUtils.base64ToFile( brand.getUploadImg() );//获取上传后返回的图片
            brand.setUrl( imgUrl );//上传图片返回路径
        }*/

        if( UtilTool.isNotBlank( brand.getType() )){
            Map<Integer,String> authCodeMap  = menuWebService.menuWebAuthCodeMap();
            //品牌简介 + 品牌文化 + 工艺 只需要一条记录
            if( authCodeMap.get( brand.getType() ).equals(Constants.BRAND_TYPE_INFO)
                    || authCodeMap.get( brand.getType() ).equals(Constants.BRAND_TYPE_CULTURE)
                    || authCodeMap.get( brand.getType() ).equals(Constants.BRAND_TYPE_TECHNOLOGY )){
                //查询是否已经存在记录
                Wrapper<Brand> queryData = new EntityWrapper<Brand>();
                queryData.eq("type", brand.getType() );
                Brand brandHis = brandService.selectOne(queryData);
                if( UtilTool.isNotBlank( brandHis ))
                    return AjaxResult.build(HttpCode.ARGS_ERROR, "类型数据已存在!");
            }
        }
        brand.setCreateTime(new Date());
        //创建人
        SelfUserDetails userDetails = (SelfUserDetails) authentication.getPrincipal();
        brand.setCreatePerson( userDetails.getUsername());
        Boolean success = brandService.insert(brand);
        return success ? AjaxResult.success() : AjaxResult.build(HttpCode.FAILED, "新增品牌信息失败!");
    }


    /**
     * 修改状态
     * @param id
     * @param status
     * @return
     */
    @PostMapping("setStatus")
    public AjaxResult<Boolean> setStatus( Integer id,Integer status){
        if (UtilTool.isBlank(id ) || UtilTool.isBlank(status))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");
        Brand brand = new Brand();
        brand.setBrandId( id );
        brand.setStatus( status );
        Boolean success = brandService.updateById( brand);
        return success ? AjaxResult.success() : AjaxResult.build(HttpCode.FAILED, "修改状态失败!");
    }
    /**
     * 获取品牌信息
     * @param brandId
     * @return
     */
    @GetMapping("findBrand")
    public AjaxResult<Brand> findBrand( Integer brandId ){
        if( UtilTool.isBlank( brandId ))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");

        Brand brand = brandService.selectById( brandId );
        return AjaxResult.success(brand);

    }

    /**
     * 修改品牌
     * @param brand
     * @return
     */
    @PostMapping("editBrand")
    public AjaxResult<Boolean> editBrand(@RequestBody Brand brand ){
        if( brand == null
                || UtilTool.isBlank( brand.getBrandId())
                || UtilTool.isBlank( brand.getBrandName())
                || UtilTool.isBlank( brand.getType())
                || UtilTool.isBlank( brand.getReleaseTime()))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");

        /*if( UtilTool.isNotBlank( brand.getUploadImg()) ){
            String imgUrl = BaseCommonUtils.base64ToFile( brand.getUploadImg() );//获取上传后返回的图片
            brand.setUrl( imgUrl );//上传图片返回路径
        }*/

        if( UtilTool.isNotBlank( brand.getType()) && UtilTool.isNotBlank(brand.getBrandId() )){
            Map<Integer,String> authCodeMap  = menuWebService.menuWebAuthCodeMap();
            //品牌简介 + 品牌文化 + 工艺 只需要一条记录
            if( authCodeMap.get( brand.getType() ).equals(Constants.BRAND_TYPE_INFO)
                    || authCodeMap.get( brand.getType() ).equals(Constants.BRAND_TYPE_CULTURE)
                    || authCodeMap.get( brand.getType() ).equals(Constants.BRAND_TYPE_TECHNOLOGY )){
                //查询是否已经存在记录
                Wrapper<Brand> queryData = new EntityWrapper<Brand>();
                queryData.eq("type", brand.getType() );
                queryData.ne("brand_id",brand.getBrandId());
                Brand brandHis = brandService.selectOne(queryData);
                if( UtilTool.isNotBlank( brandHis ))
                    return AjaxResult.build(HttpCode.ARGS_ERROR, "类型数据已存在!");
            }
        }
        Boolean success = brandService.updateById(brand);
        return success ? AjaxResult.success() : AjaxResult.build(HttpCode.FAILED, "修改品牌信息失败!");
    }

    /**
     * 根据ID删除品牌信息
     * @param brandId
     * @return
     */
    @PostMapping("delete")
    public AjaxResult<Boolean> deleteBrand( Integer brandId){

        if( UtilTool.isBlank( brandId ))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");

        Boolean success = brandService.deleteById( brandId );
        return success ? AjaxResult.success() : AjaxResult.build(HttpCode.FAILED, "删除品牌信息失败!");
    }

    /**
     * 返回品牌简介信息
     * @return
     */
    @GetMapping("findBrandBrief")
    public AjaxResult<Brand> findBrandBrief(){

        Brand  brand = brandService.findBrandBrief();
        if( UtilTool.isNotBlank( brand ))
            return AjaxResult.success(brand);
        return AjaxResult.build(HttpCode.FAILED, "获取品牌简介信息失败!");
    }


    /**
     * 返回品牌历史信息
     * @return
     */
    @GetMapping("findBrandHistory")
    public AjaxResult<List<Brand>> findBrandHistory(Integer year){

        /*if( UtilTool.isBlank( year ))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");*/
        List<Brand>  brandList = brandService.findBrandHistory(year);
        if( UtilTool.isNotBlank( brandList ))
            return AjaxResult.success(brandList);
        return AjaxResult.build(HttpCode.FAILED, "获取品牌历史信息失败!");
    }

    /**
     * 返回品牌历史年份
     * @return
     */
    @GetMapping("findBrandHistoryYear")
    public AjaxResult<Map> findBrandHistoryYear(){

        Map brandList = brandService.findBrandHistoryYearList();
        if( UtilTool.isNotBlank( brandList ))
            return AjaxResult.success(brandList);
        return AjaxResult.build(HttpCode.FAILED, "获取品牌历史年份失败!");
    }

    /**
     * 返回品牌荣誉信息
     * @return
     */
    @GetMapping("findBrandReput")
    public AjaxResult<List<Brand>> findBrandReput(Integer year){
        /*if( UtilTool.isBlank( year ))
            return AjaxResult.build(HttpCode.ARGS_ERROR, "请求参数错误!");*/
        List<Brand>  brandList = brandService.findBrandReput(year);
        if( UtilTool.isNotBlank( brandList ))
            return AjaxResult.success(brandList);
        return AjaxResult.build(HttpCode.FAILED, "获取品牌荣誉信息失败!");
    }

    /**
     * 返回品牌荣誉年份
     * @return
     */
    @GetMapping("findBrandReputYear")
    public AjaxResult<Map> findBrandReputYear(){

        Map brandList = brandService.findBrandReputYearList();
        if( UtilTool.isNotBlank( brandList ))
            return AjaxResult.success(brandList);
        return AjaxResult.build(HttpCode.FAILED, "获取品牌荣誉年份信息失败!");
    }

    /**
     * 返回品牌文化信息
     * @return
     */
    @GetMapping("findBrandCulture")
    public AjaxResult<Brand> findBrandCulture(){

        Brand  brand = brandService.findBrandCulture();
        if( UtilTool.isNotBlank( brand ))
            return AjaxResult.success(brand);
        return AjaxResult.build(HttpCode.FAILED, "获取品牌文化信息失败!");
    }

    /**
     * 返回工艺信息
     * @return
     */
    @GetMapping("findBrandTechnology")
    public AjaxResult<Brand> findBrandTechnology(){

        Brand  brand = brandService.findBrandTechnology();
        if( UtilTool.isNotBlank( brand ))
            return AjaxResult.success(brand);
        return AjaxResult.build(HttpCode.FAILED, "获取工艺信息失败!");
    }

}
